package com.lmaye.spring.framework.servlet;

import com.lmaye.spring.framework.annotation.Autowired;
import com.lmaye.spring.framework.annotation.Controller;
import com.lmaye.spring.framework.annotation.RequestMapping;
import com.lmaye.spring.framework.annotation.Service;
import com.lmaye.spring.demo.utils.StringTools;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * <pre>
 *   ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 * </pre>
 * -- DispatcherServlet 核心调度Servlet
 *
 * @author lmay.Zhou
 * @date 2019/3/16 12:21 星期六
 * @qq 379839355
 * @email lmay@lmaye.com
 */
public class DispatcherServlet extends HttpServlet {
    /**
     * Properties
     */
    private Properties properties = new Properties();

    /**
     * classNames
     */
    private List<String> classNames = new ArrayList<>();

    /**
     * ioc
     */
    private Map<String, Object> ioc = new HashMap<>();

    /**
     * handlerMapping
     */
    private Map<String, Method> handlerMapping = new HashMap<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1. 加载配置文件
        loadConfig(config.getInitParameter("contextConfigLocation"));

        // 2. 扫描所有相关的类
        scannerClass(properties.getProperty("scan.package"));

        // 3. 初始化所有相关的实例，并保存到IOC容器中
        instanceClass();

        // 4. 反射依赖注入（自动赋值）
        dependencyInject();

        // 5. 构造HandlerMapping，将url和method建立一对一的关系
        initHandlerMapping();

        // 6. 等待请求，匹配URL，定位方法，反射调用执行

        // 打印初始化日志
        System.out.println("************************* Spring Framework(Mini) init *************************");
    }

    /**
     * 1. 加载配置文件
     *
     * @param contextConfigLocation contextConfigLocation
     */
    private void loadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null != resourceAsStream) {
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 2. 扫描所有相关的类
     *
     * @param packageUrl packageUrl
     */
    private void scannerClass(String packageUrl) {
        URL url = this.getClass().getClassLoader().getResource("/" + packageUrl.replaceAll("\\.", "/"));
        File classDir = new File(url.getFile());
        for (File file : classDir.listFiles()) {
            if(file.isDirectory()) {
                scannerClass(packageUrl + "." + file.getName());
            } else {
                if(!file.getName().endsWith(".class")) {
                    continue;
                }
                classNames.add(packageUrl + "." + file.getName().replace(".class", ""));
            }
        }
    }

    /**
     * 3. 初始化所有相关的实例，并保存到IOC容器中
     */
    private void instanceClass() {
        if(classNames.isEmpty()) {
            return;
        }

        try {
            for (String className : classNames) {
                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(Controller.class)) {
                    // 默认将首字母小写作为beanName
                    String beanName = StringTools.lowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName, clazz.newInstance());
                } else if(clazz.isAnnotationPresent(Service.class)) {
                    // Service初始化并不是类的本身，如果是接口的话，而是类对应的实现类
                    // 1. 默认是类名的首字母小写作为key
                    Service service = clazz.getAnnotation(Service.class);
                    String beanName = service.value();
                    // 2. 用户自定义了beanName，那么要优先使用自定义的beanName
                    if(StringUtils.isBlank(beanName)) {
                        beanName = StringTools.lowerFirstCase(clazz.getSimpleName());
                    }
                    Object instance = clazz.newInstance();
                    ioc.put(beanName, instance);
                    // 3. 赋值的对象是接口，我们要采用一种投机取巧的方式
                    // 用接口的全类名作为key，实现类实例作为值，方便依赖注入时使用
                    Class<?>[] interfaces = clazz.getInterfaces();
                    for (Class<?> item : interfaces) {
                        if(ioc.containsKey(item.getName())) {
                            throw new Exception("The " + clazz.getName() + " for " + item.getName() + " exists !");
                        }
                        ioc.put(item.getName(), instance);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 4. 依赖注入
     */
    private void dependencyInject() {
        if(ioc.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                if(!field.isAnnotationPresent(Autowired.class)) {
                    continue;
                }
                Autowired autowired = field.getAnnotation(Autowired.class);
                String beanName = autowired.value();
                if(StringUtils.isBlank(beanName)) {
                    beanName = field.getType().getName();
                }
                // 如果private protected default，强制授权
                field.setAccessible(true);

                try {
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 5. 构造HandlerMapping，将url和method建立一对一的关系
     */
    private void initHandlerMapping() {
        if(ioc.isEmpty()) {
            return;
        }

        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(Controller.class)) {
               continue;
            }
            String baseUrl = "";
            if(clazz.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
                baseUrl = requestMapping.value();
            }

            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                if(!method.isAnnotationPresent(RequestMapping.class)) {
                    continue;
                }
                RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                // //demo//query
                String url = ("/" + baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
                handlerMapping.put(url, method);
                System.out.println("************************* Mapped " + method + "\t" + url + " *************************");
            }
        }
    }

    /**
     * Get请求
     *
     * @param req   request
     * @param resp  response
     * @throws ServletException ServletException
     * @throws IOException  IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    /**
     * Post请求
     *
     * @param req   request
     * @param resp  response
     * @throws ServletException ServletException
     * @throws IOException  IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            resp.getWriter().write("500 Exception.");
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 用户请求
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");
        // 请求路径是否存在
        if(!this.handlerMapping.containsKey(url)) {
            resp.getWriter().write("404 Not Found.");
        }

        Method method = this.handlerMapping.get(url);
        // TODO 优化处理 - 多参数
        String beanName = StringTools.lowerFirstCase(method.getDeclaringClass().getSimpleName());
        Map<String, String[]> params = req.getParameterMap();
        method.invoke(ioc.get(beanName), new Object[] {req, resp, params.get("value")[0]});
    }
}
